package cn.sam416.sample.part0601pointcut.aspectjexpressionpointcut;


import org.aopalliance.aop.Advice;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.Advisor;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.framework.ProxyFactoryBean;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

// From: https://blog.csdn.net/qq_26525215/article/details/52422395
// 6.1. Pointcut API in Spring
public class Test {
    public static void main(String[] args) {
        {
            ProxyFactoryBean factory = new ProxyFactoryBean();
            factory.setTarget(new Person());

            //声明一个aspectj切点
            AspectJExpressionPointcut cut = new AspectJExpressionPointcut();

            //设置需要拦截的方法-用切点语言来写
            cut.setExpression("execution( int cn.sam416.sample.part0601pointcut.aspectjexpressionpointcut.Person.run() )");//拦截:空参返回值为int的run方法

            Advice advice = new MethodInterceptor() {
                @Override
                public Object invoke(MethodInvocation invocation) throws Throwable {
                    System.out.println("放行前拦截...");
                    Object obj = invocation.proceed();//放行
                    System.out.println("放行后拦截...");
                    return obj;
                }
            };

            //切面=切点+通知
            Advisor advisor = new DefaultPointcutAdvisor(cut, advice);
            factory.addAdvisor(advisor);
            Person p = (Person) factory.getObject();

            p.run();
            System.out.println("----------------------------");
            p.run(10);
            System.out.println("----------------------------");
            p.say();
            System.out.println("----------------------------");
            p.sayHi("Jack");
            System.out.println("----------------------------");
            p.say("Tom", 666);
        }

        {
            System.out.println("------------XML------------");
            ApplicationContext ctx = new ClassPathXmlApplicationContext("cn/sam416/sample/part0601pointcut/aspectj-pointcut.xml");
            Person p = ctx.getBean(Person.class);
            p.run();
            System.out.println("----------------------------");
            p.run(10);
            System.out.println("----------------------------");
            p.say();
            System.out.println("----------------------------");
            p.sayHi("Jack");
            System.out.println("----------------------------");
            p.say("Tom", 666);
            System.out.println("----------------------------");


        }
    }
}
